/*
 * @Author: your name
 * @Date: 2021-09-22 09:27:12
 * @LastEditTime: 2021-09-22 15:41:15
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \数据结构\队列\链表队列\queue.c
 */
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include "queue.h"


QUEUE* createQueue()
{
    QUEUE* q = (QUEUE*)malloc(sizeof(QUEUE));
    if(!q){
        printf("no memory\n");
        return NULL;
    }
    q->front = (QNodePtr)malloc(sizeof(QNode));
    q->rear = q->front;
    if(!q->front){
        printf("no memory\n");
        return NULL;
    }
    return q;
}

bool freeQueue(QUEUE* q)
{
    if(q){
        //逐个释放
        QNodePtr tem = NULL;
        while(q->front){
            tem = q->front->next;
            free(q->front);
            q->front = tem;
        }
        free(q);
        return true;
    }
    return false;
}

bool isEmpty(QUEUE* q)
{
    if(!q){
        printf("no queue\n");
        exit(-1);
    }
    if(q->front == q->rear){
        return true;
    }
    return false;
}

void EnQueue(QUEUE* q, QElemType elem)
{
    //申请节点空间
    QNodePtr newNode = (QNodePtr)malloc(sizeof(QNode));
    newNode->value = elem;
    newNode->next = NULL;
    //入队
    q->rear->next = newNode;
    q->rear = newNode;
}

QElemType DeQueue(QUEUE* q)
{
    //空队列无法出队
    if(isEmpty(q)){
        printf("queue is empty\n");
        exit(-1);
    }
    //记录front
    QNodePtr tem = q->front;
    //出队
    q->front = q->front->next;
    //释放front
    free(tem);
    return q->front->value;
}

void clearQueue(QUEUE* q)
{
    if(!q){
        printf("no queue\n");
        exit(-1);
    }
    while(q->front != q->rear){
        DeQueue(q);
    }
}

int QueueLength(const QUEUE* q)
{
    if(!q){
        printf("no queue\n");
        exit(-1);
    }
    int num = 0;
    QNodePtr tem = q->front;
    while (tem != q->rear)
    {
        num++;
        tem = tem->next;
        printf("%d\n",tem->value);
    }
    return num;
}